package be.gnx.fogo.application.dao;

import java.util.List;

import org.hibernate.Query;

import be.gnx.fogo.application.model.Address;
import be.gnx.fogo.application.model.Country;
import be.gnx.fogo.application.util.HibernateUtil;
import be.gnx.fogo.application.util.StringUtil;

public class AddressDao extends ObjectDao<Address, Long> {

  public AddressDao() {
    super(Address.class, "id");
  }

  public Address findOrCreate(String country, String postcode, String city, String streetname, String number, String bus) {
    country = StringUtil.normalizeString(country, "ZZ");
    postcode = StringUtil.normalizeString(postcode, null);
    city = StringUtil.normalizeString(city, null);
    streetname = StringUtil.normalizeString(streetname, null);
    number = StringUtil.normalizeString(number, null);
    bus = StringUtil.normalizeString(bus, null);
    StringBuffer hql = new StringBuffer();
    hql.append("from Address where country = ? and ");
    if (postcode == null) {
      hql.append("postcode is null and ");
    } else {
      hql.append("postcode = ? and ");
    }
    if (city == null) {
      hql.append("city is null and ");
    } else {
      hql.append("city = ? and ");
    }
    if (streetname == null) {
      hql.append("streetname is null and ");
    } else {
      hql.append("streetname = ? and ");
    }
    if (number == null) {
      hql.append("number is null and ");
    } else {
      hql.append("number = ? and ");
    }
    if (bus == null) {
      hql.append("bus is null");
    } else {
      hql.append("bus = ?");
    }
    Query query = HibernateUtil.getCurrentSession().createQuery(new String(hql));
    query.setReadOnly(true);
    int index = 0;
    query.setString(index, country);
    if (postcode != null) {
      index++;
      query.setString(index, postcode);
    }
    if (city != null) {
      index++;
      query.setString(index, city);
    }
    if (streetname != null) {
      index++;
      query.setString(index, streetname);
    }
    if (number != null) {
      index++;
      query.setString(index, number);
    }
    if (bus != null) {
      index++;
      query.setString(index, bus);
    }
    List<Address> list = query.list();
    CountryDao countryDao = new CountryDao();
    Country countryEntity = countryDao.getCountry(country);
    Address address;
    if (list.size() > 0) {
      address = list.get(0);
    } else {
      address = new Address();
      address.setCountry(countryEntity);
      address.setPostcode(postcode);
      address.setCity(city);
      address.setStreetname(streetname);
      address.setNumber(number);
      address.setBus(bus);
      save(address);
    }
    return address;
  }

}
